package com.tgpms.web.tongfei.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tgpms.common.MultipartFileToFile;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.TongfeiController;
import com.tgpms.web.tongfei.entity.InPointParts;
import com.tgpms.web.tongfei.entity.Newpsnodefile;
import com.tgpms.web.tongfei.entity.Newpsnodepd;
import com.tgpms.web.tongfei.pojo.Newpsnode;
import com.tgpms.web.tongfei.pojo.R;
import com.tgpms.web.tongfei.service.IInPointPartsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * <p>
 * 控制层
 * </p>
 *
 * @author jl
 * @since 2020-11-25
 */
@Api(value = "InPointPartsController", tags = "新建管网信息检查井相关接口")
@RestController
@RequestMapping("/tongfei")
public class InPointPartsController {
    @Value("${tongfei.path}")
    private String host;
    private String addNewpsnode = "/tofly-sxgk/newpsnode"; // 新建管点url
    @Resource
    private RedisTemplate<String, Object> redis;
    @Autowired
    private IInPointPartsService inPointPartsService;

    /**
     * 新增新建管网信息检查井
     */
    @ApiOperation(value = "新增新建管网信息检查井", notes = "新增新建管网信息检查井", httpMethod = "POST")
    @PostMapping(value = "/tofly-sxgk/newpsnode", headers = "content-type=multipart/form-data")
    public Result addNewpsnode(@RequestParam(value = "newpsnode") String jsonString, HttpServletRequest request) {
        InPointParts inPointParts = JSON.parseObject(jsonString, InPointParts.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(inPointParts.getNewpsnodefileList())) {
                List<Newpsnodefile> newpsnodefileList = inPointParts.getNewpsnodefileList();
                for (int i = 0; i < newpsnodefileList.size(); i++) {
                    Newpsnodefile newpsnodefile = newpsnodefileList.get(i);
                    paramMap.put("newpsnodefileList[" + i + "].fileName", newpsnodefile.getFileName());
                    paramMap.put("newpsnodefileList[" + i + "].distance", newpsnodefile.getDistance());
                    paramMap.put("newpsnodefileList[" + i + "].latitude", newpsnodefile.getLatitude());
                    paramMap.put("newpsnodefileList[" + i + "].longitude", newpsnodefile.getLongitude());
                    paramMap.put("newpsnodefileList[" + i + "].sxCoor", newpsnodefile.getSxCoor());
                    paramMap.put("newpsnodefileList[" + i + "].syCoor", newpsnodefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(newpsnodefile.getFileName(), image);
                    images.add(image);
                }
            }

//            // 工序集合
//            if (CollectionUtil.isNotEmpty(inPointParts.getNewpsnodepdList())) {
//                List<Newpsnodepd> newpsnodepdList = inPointParts.getNewpsnodepdList();
//                for (int i = 0; i < newpsnodepdList.size(); i++) {
//                    Newpsnodepd newpsnodepd = newpsnodepdList.get(i);// 工序
//                    // 图片集合
//                    if (CollectionUtil.isNotEmpty(newpsnodepd.getNewpsnodefileList())) {
//                        List<Newpsnodefile> newpsnodefileList = newpsnodepd.getNewpsnodefileList();
//                        for (int j = 0; j < newpsnodefileList.size(); j++) {
//                            Newpsnodefile newpsnodefile = newpsnodefileList.get(j);//图片
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].fileName", newpsnodefile.getFileName());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].distance", newpsnodefile.getDistance());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].latitude", newpsnodefile.getLatitude());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].longitude", newpsnodefile.getLongitude());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].sxCoor", newpsnodefile.getSxCoor());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].syCoor", newpsnodefile.getSyCoor());
//                            File image = MultipartFileToFile.multipartFileToFile(files.get(i));
//                            paramMap.put(newpsnodefile.getFileName(), image);
//                            images.add(image);
//                        }
//                    }
//
//                    paramMap.put("newpsnodepdList[" + i + "].notes", newpsnodepd.getNotes());
//                    paramMap.put("newpsnodepdList[" + i + "].pdCode", newpsnodepd.getPdCode());
//                }
//            }

            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(inPointParts, false, true));
            paramMap.remove("newpsnodefileList");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + addNewpsnode)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地新增
                String json = JSON.toJSONString(r.getResult());
                Newpsnode data = JSON.parseObject(json, Newpsnode.class);
                inPointParts.setRowstamp(String.valueOf(data.getId()));
                inPointParts.setInsertUser(this.getUsername(token));
                return inPointPartsService.addInPointParts(inPointParts);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 修改新建管网信息检查井
     */
    @ApiOperation(value = "修改新建管网信息检查井", notes = "修改新建管网信息检查井", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/updateNewpsnode")
    public Result updateNewpsnode1(@RequestParam(value = "newpsnode") String jsonString, HttpServletRequest request) {
        Newpsnode newpsnode = JSON.parseObject(jsonString, Newpsnode.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(newpsnode.getNewpsnodefileList())) {
                List<Newpsnodefile> newpsnodefileList = newpsnode.getNewpsnodefileList();
                for (int i = 0; i < newpsnodefileList.size(); i++) {
                    Newpsnodefile newpsnodefile = newpsnodefileList.get(i);
                    paramMap.put("newpsnodefileList[" + i + "].fileName", newpsnodefile.getFileName());
                    paramMap.put("newpsnodefileList[" + i + "].distance", newpsnodefile.getDistance());
                    paramMap.put("newpsnodefileList[" + i + "].latitude", newpsnodefile.getLatitude());
                    paramMap.put("newpsnodefileList[" + i + "].longitude", newpsnodefile.getLongitude());
                    paramMap.put("newpsnodefileList[" + i + "].sxCoor", newpsnodefile.getSxCoor());
                    paramMap.put("newpsnodefileList[" + i + "].syCoor", newpsnodefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(newpsnodefile.getFileName(), image);
                    images.add(image);
                }
            }

//            // 工序集合
//            if (CollectionUtil.isNotEmpty(newpsnode.getNewpsnodepdList())) {
//                List<Newpsnodepd> newpsnodepdList = newpsnode.getNewpsnodepdList();
//                for (int i = 0; i < newpsnodepdList.size(); i++) {
//                    Newpsnodepd newpsnodepd = newpsnodepdList.get(i);// 工序
//                    // 图片集合
//                    if (CollectionUtil.isNotEmpty(newpsnodepd.getNewpsnodefileList())) {
//                        List<Newpsnodefile> newpsnodefileList = newpsnodepd.getNewpsnodefileList();
//                        for (int j = 0; j < newpsnodefileList.size(); j++) {
//                            Newpsnodefile newpsnodefile = newpsnodefileList.get(j);//图片
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].fileName", newpsnodefile.getFileName());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].distance", newpsnodefile.getDistance());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].latitude", newpsnodefile.getLatitude());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].longitude", newpsnodefile.getLongitude());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].sxCoor", newpsnodefile.getSxCoor());
//                            paramMap.put("newpsnodepdList[" + i + "].newpsnodefileList[" + j + "].syCoor", newpsnodefile.getSyCoor());
//                            File image = MultipartFileToFile.multipartFileToFile(files.get(i));
//                            paramMap.put(newpsnodefile.getFileName(), image);
//                            images.add(image);
//                        }
//                    }
//
//                    paramMap.put("newpsnodepdList[" + i + "].notes", newpsnodepd.getNotes());
//                    paramMap.put("newpsnodepdList[" + i + "].pdCode", newpsnodepd.getPdCode());
//                }
//            }

            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(newpsnode, false, true));
            paramMap.remove("newpsnodepdList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.put(host + addNewpsnode)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地修改
                String json = JSON.toJSONString(r.getResult());
                Newpsnode data = JSON.parseObject(json, Newpsnode.class);
                InPointParts inPointParts = inPointPartsService.getInPointPartsByRowstamp(String.valueOf(data.getId()));
                BeanUtil.copyProperties(data, inPointParts, "id");
                inPointParts.setModifyUser(this.getUsername(token));
                inPointParts.setModifyDate(new Date());
                return inPointPartsService.updateInPointParts(inPointParts);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 分页查询新建管网信息检查井
     */
    @ApiOperation(value = "分页查询新建管网信息检查井", notes = "分页查询新建管网信息检查井", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpsnode/page")
    public Result page(Newpsnode newpsnode, HttpServletRequest request) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(newpsnode, false, true);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/newpsnode/page", paramMap, request);
    }

    /**
     * 查询固件最新的扫描数据
     */
    @ApiOperation(value = "查询固件最新的扫描数据", notes = "查询固件最新的扫描数据", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpsnode/getNewScanInfo")
    public Result getNewScanInfo(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return TongfeiController.normalGet("/tofly-sxgk/newpsnode/getNewScanInfo", paramMap, request);
    }

    /**
     * 查询同类型人员固件最新的扫描数据
     */
    @ApiOperation(value = "查询同类型人员固件最新的扫描数据", notes = "查询同类型人员固件最新的扫描数据", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpsnode/getNewScanInfoByType")
    public Result getNewScanInfoByType(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return TongfeiController.normalGet("/tofly-sxgk/newpsnode/getNewScanInfoByType", paramMap, request);
    }

    private String getUsername(String token) {
        return (String) redis.opsForValue().get(token);
    }
}
